<script>
import store from "../../store/index.js";
import {ElMessage, genFileId} from "element-plus";
import {Plus} from "@element-plus/icons-vue";
import request from "../../utils/Request.js";

export default {
  name: "InfoCard",
  components: {Plus},
  computed: {
    store() {
      return store
    }
  },
  data() {
    return {
      disableButton: false,
      formData: new FormData(),
      info: {
        nickname: this.$store.state.user.nickname,
        phone: this.$store.state.user.phone == null ? '' : this.$store.state.user.phone
      },
      rules: {
        nickname: [
          {
            validator: (rule, value, callback) => {
              if (!new RegExp("^[\u4e00-\u9fa5_a-zA-Z0-9-]+$").test(value))
                callback(new Error('请输入正确的名称，且不能包含除_-以外的字符！'))
              else
                callback()
            }
          }
        ],
        phone: [
          {
            validator: (rule, value, callback) => {
              console.log(value)
              if (value !== '' && !new RegExp("^1[3-9]\\d{9}$").test(value))
                callback(new Error('请输入正确的电话号码！'))
              else
                callback()
            }, trigger: 'blur'
          }
        ]
      },
      tempAvatarUrl: null,
      fileReader: new FileReader()
    }
  },
  methods: {
    request,
    onChangeAvatar(uploadFile) {
      let rawFile = uploadFile.raw;
      let upload = this.$refs['uploadRef'];
      if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('图片必须是jpg或png类型的!')
        upload.clearFiles()
        return;

      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过2MB!')
        upload.clearFiles()
        return;
      }
      this.formData.set('file', rawFile)
      this.fileReader.readAsDataURL(rawFile)
    },
    handleExceed(files) {
      let upload = this.$refs['uploadRef'];
      upload.clearFiles()
      const file = files[0]
      file.uid = genFileId()
      upload.handleStart(file)
    },
    onSubmit() {
      let form = this.$refs['infoFormRef'];
      let upload = this.$refs['uploadRef'];

      form.validate(isValid => {
        if (isValid) {

          this.formData.set('nickname', this.info.nickname)
          this.formData.set('phone', this.info.phone)
          request({
            method: 'post',
            url: '/api/uaa/user/info',
            data: this.formData,
            headers: {'Content-Type': 'multipart/form-data'}
          })
              .then(resp => {
                let data = resp.data;
                if (data.code === 0) {
                  ElMessage.success('修改信息成功')
                } else {
                  ElMessage.error(data.msg)
                }
              })
              .catch(err => {
                console.log(err)
                ElMessage.error('出现未知错误，请重试！')
              })

        }
      })
    },
  },
  created() {
    this.fileReader.addEventListener("load",
        () => {
          this.tempAvatarUrl = this.fileReader.result;
        },
        false)
  }
}
</script>

<template>
  <el-card>
    <el-form
        ref="infoFormRef"
        status-icon
        :model="info"
        :rules="rules"
    >
      <el-form-item label="头像">
        <el-avatar :src="tempAvatarUrl == null ? store.state.user.avatarUrl : tempAvatarUrl"
                   fit="cover"
                   :size="130"
        >
        </el-avatar>
        <el-upload ref="uploadRef"
                   :auto-upload="false"
                   :limit="1"
                   :show-file-list="false"
                   :on-exceed="handleExceed"
                   @change="onChangeAvatar"
                   :on-remove="() => this.formData.delete('file')"
        >
          <el-button type="primary" class="ml-20">
            上传头像
          </el-button>
        </el-upload>
      </el-form-item>

      <el-form-item prop="nickname" key="nickname" label="名称">
        <el-input class=" mb-5" size="large" v-model="info.nickname"
                  type="text"
                  clearable maxlength="64"/>
      </el-form-item>

      <el-form-item prop="phone" key="phone" label="号码">
        <el-input class=" mb-5" size="large" v-model="info.phone"
                  placeholder="手机号码"
                  type="tel"
                  clearable maxlength="11"/>
      </el-form-item>

      <el-form-item key="submitSave" label-width="40">
        <el-button type="primary" @click="onSubmit" :disabled="disableButton"
                   color="#eebe77"
        >
          保存修改
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style scoped>

</style>